import { EntrySynchronizationMethod, intl } from '@/utils';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Menu, Modal, Progress, Row, Select } from 'antd';
import { Button } from 'devextreme-react/button';
import DropDownButton from 'devextreme-react/drop-down-button';
import TreeView from 'devextreme-react/tree-view';
import notify from 'devextreme/ui/notify';
import moment from 'moment';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import type { DraggableData, DraggableEvent } from 'react-draggable';
import Draggable from 'react-draggable';
import { useModel } from 'umi';
import ChangeTemplatePopup from '~/public/cpas-business/components-bs/components/TemplatePopup/ChangeTemplatePopup';
import SaveTemplatePopup from '~/public/cpas-business/components-bs/components/TemplatePopup/SaveTemplatePopup';
import { CpasIcon, DevPopup, LayoutB } from '~/public/cpas-ui';
import DevDefaultPopup from '~/public/cpas-ui/components-ui/express-components/DevPopup';
import { msgError } from '../../utils/msg';
import { getReportList } from '../batchSettings/service';
import './index.less';
import {
  createReport,
  createVersion,
  exportExcelReport,
  exportReport,
  exportTempldate,
  getDataId,
  getSeekAuditReportTemplate,
  getVersions,
  gnoteTreeList,
  initTemplate,
  notesIsEmpty,
  openReport,
  queryAnyFileIfExistInDiskRelativePath,
  saveTemplate,
} from './service';
import type { CreateReportProgressInfo, ProgressInfo } from './typings';

const ReportBuilder1: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { dbname, sjxmbh, zcbfid, sjnd, XMType, bsdw } = initialState?.curPart;
  const oneLevelItem = [
    {
      key: 1,
      label: '目录与正文',
    },
    {
      key: 2,
      label: '财务报表附注',
    },
    {
      key: 3,
      label: '财务报表',
    },
  ];
  let fileNameArr = ['', '报告正文.docx', '报告附注.docx', '财务报表.xlsx'];
  const [processPanelVisible, setProcessPanelVisible] = useState(false);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [versionList, setVersionList] = useState<string[]>([]);

  // const [currentTemplateName, setCurrentTemplateName] = useState('');
  // const [isDisclosureTableListVisible, setIsDisclosureTableListVisible] = useState(false);
  const [disclosureTablesData, setDisclosureTablesData] = useState([]);
  //const [selectedDisclosureTable, setSelectedDisclosureTable] = useState([]);
  const selectedDisclosureTable = useRef([]); // 选中的note
  const [dialogTipText, setDialogTipText] = useState('');
  const [isCreateReportSuccess, setIsCreateReportSuccess] = useState(false);
  // const [currentFileName, setCurrentFileName] = useState('报告正文.docx');
  const [currentMenuKey, setCurrentMenuKey] = useState('1');
  const [dataId, setDataId] = useState('2023');
  const versionDialogRef = useRef<any>(null);
  const treeViewRef = useRef<any>(null);
  const saveTemplatePopupRef = useRef<any>();
  const changeTemplatePopupRef = useRef<any>();
  const timer = useRef<any>();
  const projectBase = `/ProjectData/${sjxmbh}/${zcbfid}/报告/`;
  const projectTemplatePath = `${projectBase}/Template`;
  const [disabled, setDisabled] = useState(true);
  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });
  const [seconds, setSeconds] = useState(0);
  const [isReportOpen, setIsReportOpen] = useState(false);
  const draggleRef = useRef<HTMLDivElement>(null);

  //进度条相关

  const [progressInfo, setProgressInfo] = useState<ProgressInfo>({
    progressText: '',
    progressValue: 0,
  });
  const allNoteList = useRef<any>();
  const mergeStartTime = useRef<number>(0);
  //const vserionNote = useRef({ noteList: [], cellDataList: [] });  // 存储历史版本的选中状态，随时可变
  const allNotes = useRef({ noteList: [], cellDataList: [] }); // 存储初始的节点，存储当前版本的选中状态吗，全局不变

  const [currentVersion, setCurrentVersion] = useState<string>('请选择');
  const [isError, setIsError] = useState<string>('');
  const userInfoStr = window.localStorage.cpasUserInfo;
  const userInfo = JSON.parse(userInfoStr);
  //@ts-ignore
  const password = window.main.cryptoUtil(userInfo.aesPassword);

  // 一级侧边栏导航点击事件
  const onItemClick = async (e: any) => {
    setCurrentMenuKey(e.key);
  };

  const getNoteVersion = async (basePath: string, version: string) => {
    //@ts-ignore
    let notes_arr = await window.main.mainObject.loadJsonFromFile(
      `${window.main.mainObject.getAppPath()}${basePath}\\${version}\\Note${version}.json`,
    );

    if (notes_arr?.notes) {
      return notes_arr.notes;
    } else {
      return null;
    }
  };

  const SaveNoteVersion = async (basePath: string, version: string, data: any) => {
    //@ts-ignore
    let config = await window.main.mainObject.saveContentToFile(
      { notes: data },
      `${window.main.mainObject.getAppPath()}${basePath}\\${version}\\Note${version}.json`,
    );
  };
  const treeViewSelectionChanged = async (e: any) => {
    syncSelection(e.component);
  };
  const syncSelection = (treeView: any) => {
    const selectedEmployees = treeView.getSelectedNodes().map((node: any) => node.itemData);
    selectedDisclosureTable.current = selectedEmployees; // 生成报告提交选中节点
  };

  const doCreateReport = async () => {
    console.log(initialState, 'initialState');
    startSetInterval();
    const noteCount = selectedDisclosureTable?.current?.length ?? 0;
    if (noteCount == 0) {
      return msgError(
        intl('cs.notSelectReportNote', '还没有选择附注,请在【左侧->财务报表附注】中选择.'),
      );
    }
    setIsError('');
    setSeconds(0);
    setProcessPanelVisible(true);
    const ids = selectedDisclosureTable.current.map((item: any) => item.id);
    const startTime = performance.now();
    mergeStartTime.current = startTime;
    //setMergeStartTime(startTime);
    const params = {
      projectId: sjxmbh,
      partId: zcbfid,
      dataId,
      ids,
      zcbfid,
      id: mergeStartTime.current,
      noteList: allNoteList.current.map((a: any) => {
        return { ...a, id: `${a.id}-zl`, fid: `${a.fid}-zl`, pid: a.pid ? `${a.pid}-zl` : null };
      }),
    };
    //存在这个方法,用新的,消息通讯方式
    //@ts-ignore
    if (window.main?.createReport) {
      //@ts-ignore
      await window.main?.createReport(params); //在 window_message_event 中处理进度数据
    } else {
      //使用http请请求方式
      console.log('使用http请请求方式,开始创建报告');
      const data = await createReport(params);
      let dataLsit = await getReportList({ dbname: zcbfid, isDesc: true });
      let res = await exportExcelReport({
        resSetting: dataLsit.data,
        dbname: zcbfid,
        //@ts-ignore
        directoryPath: `${window.main.mainObject.getAppPath()}${projectBase}Generated`,
        projectName: bsdw,
        zcbfid: zcbfid,
      });
      console.log(res, 'res');
      if (!res.ok) {
        notify('生成财务报表失败', 'error', 5000);
      }
      await createReportOnFinsh(startTime, selectedDisclosureTable.current);
    }
  };
  //创建结束处理
  async function createReportOnFinsh(startTime: number, selectedDisclosureTableV1: any) {
    stopSetInterval();
    console.log(
      '报告创建结束,开始处理',
      selectedDisclosureTableV1,
      selectedDisclosureTable.current,
    );

    //SaveNewVersionReport('当前版本', selectedDisclosureTable.current);
    await SaveNoteVersion(projectBase, 'Generated', {
      noteList: allNotes.current.noteList,
      cellDataList: selectedDisclosureTable.current,
    } as any);
    // await initVersions()
    // onOpenVersionSelect('当前版本')
    // setCurrentVersion('当前版本');
    setIsReportOpen(false);
    const endTime = performance.now();
    //耗时秒
    const takeSeconds = '(耗时 ' + ((endTime - startTime) / 1000).toFixed(0) + ' 秒)';

    // console.log(isError)
    setIsCreateReportSuccess(true);
    setDialogTipText(` 报告生成成功${takeSeconds}，是否现在立即打开生成的报告文档？`);

    setProcessPanelVisible(false);
    setDialogVisible(true);
  }

  async function initVersions() {
    const data = await getVersions({ projectId: sjxmbh, partId: zcbfid });
    if (data.data?.length) {
      //1,Generated
      //2,Generated,'当前版本'
      //3,Generated,'当前版本', xxxx
      //1,currentVersion === 'Generated' ? '当前版本' : currentVersion
      const arr = data.data.filter((a: any) => a !== 'Generated' && a !== '当前版本');
      setVersionList(['当前版本'].concat(arr) as any);
      //setCurrentVersion('当前版本');
      return data.data;
    } else {
      setVersionList([].concat([]));
      return [];
    }
  }

  async function initTemplateOnLoad() {
    let data = await getSeekAuditReportTemplate({ zcbfid });
    // console.log('当前模板：', data.data.AuditReportTemplate);
    const templateName = data.data.AuditReportTemplate;
    data = await queryAnyFileIfExistInDiskRelativePath({
      filePath: projectTemplatePath,
    });
    // setCurrentTemplateName(templateName);
    //console.log('1111', data);
    if (!data.data) {
      initTemplate({
        templateName,
        copyFilesToWhere: projectTemplatePath,
      });
    }
  }

  async function initDisclosureTables() {
    let dataID = await getDataId({ dbName: zcbfid });
    if (!dataID.ok || dataID.data.length == 0) {
      return msgError(intl('rp.notFoundYear', '未获取到年度'));
    }
    setDataId(dataID.data[0].Data_ID);
    const data = await gnoteTreeList({
      zcbfid: zcbfid,
      Data_ID: dataID.data[0].Data_ID,
      dbName: zcbfid,
    });
    // let Celldata = await CellDataTidList({ zcbfid: zcbfid, Data_ID: dataID.data[0].Data_ID, dbName: zcbfid });
    // debugger
    let Celldata: any = await notesIsEmpty({ zcbfid: zcbfid, dataId: dataID.data[0].Data_ID });

    if (Celldata.data?.length) {
      Celldata = Celldata.data.map((a: any) => {
        return { tid: a.fid };
      });
      allNotes.current.noteList = data.data;
      allNotes.current.cellDataList = Celldata;
      setCurrentNote(data.data, Celldata, true);
      //setCurrentVersion('请选择');
      return data.data;
    } else {
      notify('附注列表无数据，请先初始化附注分析', 'error', 1000);
    }
  }

  async function setCurrentNote(note: [], tids: object[], isF?: boolean) {
    const items = note.map((item: any) => {
      if (item.pid === null) {
        delete item.pid;
      }
      if (isF) {
        item.selected =
          item.isDisclosure === true && !tids.map((a: any) => a.tid || a.id).includes(item.id); // 有数据的，有表的选中
      } else {
        item.selected =
          item.isDisclosure === true && tids.map((a: any) => a.tid || a.id).includes(item.id); // 有数据的，有表的选中
      }

      return item;
    });
    setDisclosureTablesData(items as []);
    const selectedNodes = items.filter((item: any) => {
      return item.selected;
    });
    selectedDisclosureTable.current = selectedNodes as [];
    allNoteList.current = items as [];
  }

  const startSetInterval = useCallback(() => {
    // const start = performance.now();
    timer.current = setInterval(() => {
      const cur = performance.now();
      setSeconds(Math.trunc((cur - mergeStartTime.current) * 0.001));
    }, 900);
  }, [processPanelVisible]); // 依赖进度条
  const stopSetInterval = useCallback(() => {
    return clearInterval(timer.current);
  }, []);
  useEffect(() => {
    initVersions(); // 首次进入查询是否存在版本
    initDisclosureTables();
    initTemplateOnLoad();
  }, []);

  const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };

  //消息 ipcRenderer.on('exportImportData-progress', (event, params) =>
  async function window_message_event(e: any) {
    const params: CreateReportProgressInfo = e.data; //jsonObject
    console.log(params.isError ? params : '');
    if (params.msgType == 'createReport-progress' && params.xmbh === sjxmbh) {
      if (params.id === mergeStartTime.current) {
        updateMergeProgressInfo(params.progressValue, params.progressText);
        // console.log(params.progressText,params.progressText.includes("进程"))
        if (params.isError) {
          stopSetInterval();
          if (params.retData || params.progressText.includes('生成报告失败')) {
            console.log(isError, params.retData, '1');

            setIsReportOpen(false);
            setProcessPanelVisible(false);
            setIsCreateReportSuccess(false);
            setDialogVisible(true);
            setDialogTipText(`报告生成出错：${params.retData || params.progressText}`);
          } else {
            setIsError(isError.concat(`${params.retData || params.progressText}`));
          }
          // console.log(isError,params.retData)
        } else if (params.isFinished) {
          createReportOnFinsh(mergeStartTime.current, []);
        }
        if (params.progressText.includes('附注索引生成完成')) {
          let dataLsit = await getReportList({ dbname: zcbfid, isDesc: true });
          let res = await exportExcelReport({
            resSetting: dataLsit.data,
            dbname: zcbfid,
            //@ts-ignore
            directoryPath: `${window.main.mainObject.getAppPath()}${projectBase}Generated`,
            projectName: bsdw,
            zcbfid: zcbfid,
          });
          console.log(res, 'res');
          if (!res.ok) {
            stopSetInterval();
            notify('生成财务报表失败', 'error', 5000);
          }
        }
      }
    } else {
      if (params.xmbh) {
        stopSetInterval();
        // TODO 如果不加这个判断，现在任何调用浏览器下载弹出的窗口. 都会提示以下错误 , 这需要整改，不能用这种方式来判断报告生成是否有其他项目正在进行
        notify(`有正在生成的其他项目【${params.xmbh}】,请不要同时生成`, 'error', 2000);
      }
    }
  }
  useEffect(() => {
    //接受electron的proload.ts中下载事件 ipcRenderer.on('downloadStart'
    window.addEventListener('message', window_message_event);
    return () => {
      window.removeEventListener('message', window_message_event);
    };
    //treeViewRef.current.
  }, []);

  /**确认生成报告 */
  /**
   *
   * @param e 点击事件
   * @param mergeStartTime 生成报告开始时间
   */
  const exportReportOrTem = async (e?: any) => {
    //@ts-ignore
    const result = await window.electronComponents.openDirectoryDialog();
    // console.log(result)
    if (!result.canceled) {
      // let version = currentVersion ? currentVersion : 'Generated';
      // if (version === '当前版本') {
      //   version = 'Generated';
      // }
      const fileUrl = `${result.filePaths[0]}\\${
        e.itemData === '导出报告' ? '审计报告' : '报告模板'
      }`;

      const exportfile = async () => {
        const res = await exportReport({
          projectId: sjxmbh,
          partId: zcbfid,
          version: currentVersion,
          targetDir: fileUrl,
          isTemplate: e.itemData === '导出报告' ? false : true,
        });
        if (res.ok) {
          notify('导出成功', 'success');
        } else {
          notify('导出失败,请选择版本，或者检查该版本下的文件是否关闭', 'error');
        }
      };
      //@ts-ignore
      if (window.main.fileExists(fileUrl)) {
        //@ts-ignore
        const fileexists = window.main.msgYesNo('该路径下已存在此文件，是否覆盖');
        if (fileexists) {
          exportfile();
        }
      } else {
        exportfile();
      }
    }
  };

  /***
   * * 事件函数： openReportOrtem
   */
  const openReportOrtem = async (e?: any) => {
    const params: any = {
      projectId: sjxmbh,
      partId: zcbfid,
      fileName: fileNameArr[parseInt(currentMenuKey)],
      isTemplate: e === '打开报告' ? false : true,
      version: currentVersion,
    };
    // if (currentVersion && currentVersion != '当前版本') {
    //   params.version = currentVersion;
    // }
    const data = await openReport(params);
    if (!data.ok) {
      notify('未找到报告相关的文件，请确认选择了正确的版本和报告已经生成。', 'error');
    }
  };

  /**
   *
   * 事件函数： onClickSaveNewVersionReport
   */

  const onClickSaveNewVersionReport = async (e: any, isGenerate: boolean = false) => {
    console.log(selectedDisclosureTable.current, '?');
    if (versionList.length) {
      if (versionList.includes(e)) {
        //@ts-ignore
        const fileexists = window.main.msgYesNo('此版本已经存在，是否覆盖');
        if (fileexists) {
          await SaveNewVersionReport(e, selectedDisclosureTable.current);
        }
      } else {
        await SaveNewVersionReport(e, selectedDisclosureTable.current);
      }
    } else {
      notify('当前还未生成报告');
    }
  };

  /**
   * onDeleteVersion
   */
  const onclickDeleteVersion = async (e: any) => {
    //@ts-ignore
    const fileexists = window.main.msgYesNo(`此版本${currentVersion}，是否删除`);
    if (fileexists) {
      try {
        //@ts-ignore
        window.main.mainObject.deleteFolder(
          `${window.main.mainObject.getAppPath()}${projectBase}\\${currentVersion}`,
          false,
        );
        //  await initVersions()
        setVersionList(versionList.filter((item: any) => item !== currentVersion) as any);
        //setCurrentVersion('当前版本') ;
        onOpenVersionSelect('当前版本');
        notify('删除成功');
      } catch (error) {
        notify('删除失败');
      }
    }
  };

  /**
   *
   * onClickOpenSaveVersion
   */
  const onClickOpenSaveVersion = (e: any) => {
    versionDialogRef.current.show({
      title: '保存为新版本',
      value: moment().format('YYYYMMDDHHmm'),
      okCallback: (e: any) => onClickSaveNewVersionReport(e),
    });
  };

  /**
   * onOpenVersionSelect
   */
  const onOpenVersionSelect = async (value: any) => {
    if (value === '当前版本') {
      value = 'Generated';
    }
    let vserionNote = await getNoteVersion(projectBase, value);
    if (vserionNote) {
      setCurrentNote(vserionNote.noteList, vserionNote.cellDataList);
    } else {
      // 没有版本就是当前版本，兼容历史版本
      setCurrentNote(allNotes.current.noteList as [], allNotes.current.cellDataList, true);
    }
    setCurrentVersion(value);
  };

  /**
   * math SaveNewVersionReport
   */
  const SaveNewVersionReport = async (e: any, selectNotedata: any) => {
    let dd = await createVersion({
      projectId: sjxmbh,
      partId: zcbfid,
      version: e,
    });
    console.log(selectedDisclosureTable.current, '?????');
    await SaveNoteVersion(projectBase, e, {
      noteList: allNotes.current.noteList,
      cellDataList: selectNotedata,
    } as any);
    if (dd.ok && dd.data === '') {
      notify(`版本 ${e} 保存成功`);
      await initVersions();
    } else {
      notify(`版本保存失败，请关闭文件`);
    }
  };

  //更新合并进度
  const updateMergeProgressInfo = (
    progressValue: number, //进度数据[0..100]
    progressText?: string, //进度说明
  ) => {
    progressText = progressText;
    setProgressInfo({ progressValue, progressText });
  };
  const ReportTypeList = () => {
    return (
      <div>
        <Menu
          items={oneLevelItem}
          defaultSelectedKeys={[currentMenuKey]}
          onClick={async (e) => {
            await onItemClick(e);
          }}
        />
      </div>
    );
  };
  return (
    <div style={{ height: 'calc(100vh - 104px)' }} id="report-page-container">
      <Modal
        open={isReportOpen}
        className="report-modal"
        keyboard={false}
        maskClosable={false}
        closable={!processPanelVisible}
        width={500}
        //centered={true}
        destroyOnClose={true}
        forceRender={true}
        title={
          <div
            style={{ cursor: 'move' }}
            onMouseOver={() => {
              if (disabled) {
                setDisabled(false);
              }
            }}
            onMouseOut={() => {
              setDisabled(true);
            }}
          >
            <ExclamationCircleOutlined style={{ color: 'orange' }} /> 确认
          </div>
        }
        onOk={doCreateReport}
        onCancel={() => {
          setProcessPanelVisible(false);
          setIsReportOpen(false);
        }}
        cancelButtonProps={{ disabled: processPanelVisible }}
        okButtonProps={{
          loading: processPanelVisible,
          disabled: processPanelVisible,
        }}
        okText="开始生成"
        cancelText="取消"
        modalRender={(modal) => (
          <Draggable
            disabled={disabled}
            bounds={bounds}
            nodeRef={draggleRef}
            onStart={(event, uiData) => onStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        )}
      >
        <div className="report-content">
          已选择附注 {selectedDisclosureTable?.current?.length} 个, 生成报告需要几分钟,
          {processPanelVisible ? '请稍候...' : '是否继续?'}
        </div>
        <div style={{ height: 40, display: processPanelVisible ? 'block' : 'none' }}>
          <Progress percent={progressInfo.progressValue} showInfo={false} />
          <div>
            已完成 {progressInfo.progressValue.toFixed(0)}% 耗时{seconds.toFixed(0)} 秒
            {progressInfo.progressText}
          </div>
        </div>
      </Modal>

      <DevDefaultPopup.Input ref={versionDialogRef} />
      <DevPopup.Logic
        width={500}
        height={250}
        visible={dialogVisible}
        title="提示"
        okCallbackShow={!isCreateReportSuccess}
        cancelText="否"
        okText={isCreateReportSuccess ? '是' : '确定'}
        onOK={async () => {
          // console.log('on ok');
          setDialogVisible(false);
          if (isCreateReportSuccess) {
            await openReport({
              projectId: sjxmbh,
              partId: zcbfid,
              fileName: '报告附注.docx',
            });
          }
        }}
        // cancelDisabled
        onCancel={() => {
          setDialogVisible(false);
        }}
        onHiding={() => setDialogVisible(false)}
      >
        {() => {
          return (
            <div style={{ overflowY: 'auto', height: '85px' }}>
              {isError.length > 0 ? <div>{isError}</div> : ''}
              <br />
              <div>{dialogTipText}</div>
            </div>
          );
        }}
      </DevPopup.Logic>

      <SaveTemplatePopup
        ref={saveTemplatePopupRef}
        okCallback={async (data: any) => {
          //console.log(data, '@@@ 保存模板');
          const res = await saveTemplate({
            templateName: data,
            files: projectTemplatePath,
            isInsertDB: false,
          });
          if (res.ok) {
            saveTemplatePopupRef.current.reloadTemplate();
            notify(`保存模板成功！`, 'success', 2000);
          } else {
            notify(`保存模板失败！`, 'success', 2000);
          }
        }}
        cancelCallback={() => {
          //console.log('@@@ ， 取消');
        }}
      />

      <ChangeTemplatePopup
        ref={changeTemplatePopupRef}
        okCallback={async (data: any) => {
          //console.log(data, '@@@ 切换模板');
          // setCurrentTemplateName(data);
          const res = await initTemplate({
            templateName: data,
            copyFilesToWhere: projectTemplatePath,
          });
          if (res.ok) {
            notify(`切换模板成功！`, 'success', 2000);
          } else {
            notify(`切换模板失败！`, 'success', 2000);
          }
        }}
        cancelCallback={() => {
          //console.log('@@@ ， 取消');
        }}
        changeData={{
          cloudTempType: '报告模板',
        }}
      />
      <Row align={'middle'} wrap={false} className="report-top-box">
        <div className="report-lf">报告生成</div>
        <div className="report-ri">
          <div style={{ display: 'flex' }}>
            <Button icon="clock" onClick={onClickOpenSaveVersion} />
            <div style={{ display: 'flex', alignItems: 'center', marginLeft: 5 }}>
              <div style={{ whiteSpace: 'nowrap' }}>版本名称：</div>
              <Select
                style={{ width: 150, height: 'auto' }}
                value={currentVersion === 'Generated' ? '当前版本' : currentVersion}
                options={versionList.map((a: any) => {
                  return { value: a, label: a };
                })}
                onChange={onOpenVersionSelect}
              />

              {/* <Button icon='clear' onClick={onclickDeleteVersion}></Button> */}
              {currentVersion !== '请选择' && currentVersion !== 'Generated' ? (
                <CpasIcon
                  type="icon-delete"
                  sz="lg"
                  style={{ marginLeft: 20 }}
                  onClick={onclickDeleteVersion}
                />
              ) : (
                ''
              )}

              <Button
                text="打开报告"
                type="default"
                stylingMode="contained"
                onClick={() => {
                  openReportOrtem('打开报告');
                }}
              />
              <Button
                text="打开模板"
                type="normal"
                stylingMode="outlined"
                onClick={openReportOrtem}
                visible={currentMenuKey != '3' ? true : false}
              />
            </div>
          </div>
          <div>
            <div style={{ width: '100%', textAlign: 'right' }}>
              <Button
                width={100}
                text="生成报告"
                type="default"
                stylingMode="contained"
                onClick={() => {
                  //加提示 add by csb
                  /*应测试要求这个弹窗提示不友好，下掉elctron的提示弹窗
                  if (window.main.msgYesNo('生成报告需要几分钟,是否继续?')) {
                    doCreateReport();
                  }*/

                  setIsError('');
                  updateMergeProgressInfo(0, '');
                  setIsReportOpen(true);
                }}
              />
              <DropDownButton
                style={{ height: '34px', Width: '100px', marginLeft: '8px', marginRight: '8px' }}
                text="导出"
                dropDownOptions={{
                  width: 120,
                }}
                onItemClick={exportReportOrTem}
                items={['导出报告', '导出模板']}
              />
              <DropDownButton
                style={{
                  height: '34px',
                  Width: '100px',
                  marginLeft: '8px',
                  marginRight: '8px',
                }}
                text="模板"
                dropDownOptions={{
                  width: 120,
                }}
                onItemClick={async (e: any) => {
                  if (e.itemData === '切换模板') {
                    const data = await getSeekAuditReportTemplate({ zcbfid });
                    const templateName = data.data.AuditReportTemplate;
                    changeTemplatePopupRef.current.showTemplate({ templateName });
                  } else if (e.itemData === '保存模板') {
                    saveTemplatePopupRef.current.showTemplate();
                  } else {
                    //@ts-ignore
                    const { canceled, filePaths } = await window.electronComponents.openFilesDialog(
                      'docx',
                    );
                    if (!canceled && filePaths.length < 3) {
                      if (
                        filePaths[0].endsWith('报告附注.docx') ||
                        filePaths[0].endsWith('报告正文.docx')
                      ) {
                        const res = await exportTempldate({
                          projectId: sjxmbh,
                          partId: zcbfid,
                          targetDir: filePaths,
                        });
                        if (res.ok) {
                          notify('导入成功');
                        } else {
                          notify('导入失败', 'error');
                        }
                      } else {
                        notify('导入文件过多', 'error');
                      }
                    }
                  }
                }}
                items={['切换模板', '保存模板', '导入项目模板']}
              />{' '}
              {XMType === '联机审计项目' ? (
                <Button
                  width={140}
                  text="上传至合并试算"
                  type="normal"
                  stylingMode="outlined"
                  visible={false}
                  onClick={() => {
                    EntrySynchronizationMethod({
                      usercode: initialState?.curUser.usercode,
                      password: password,
                      zcbfid: zcbfid,
                      BusID: '',
                      BusType: 3,
                    });
                  }}
                ></Button>
              ) : (
                ''
              )}
              <Button
                className="defaultReloadBtnWhite report-builder-button"
                style={{ height: 34 }}
                render={() => (
                  <CpasIcon type="icon-refresh" fontSize={16} style={{ verticalAlign: 'middle' }} />
                )}
                onClick={async () => {
                  await initDisclosureTables();
                  notify('数据刷新成功');
                }}
              />
            </div>
          </div>
        </div>
      </Row>
      <div className={currentMenuKey === '2' ? 'finance-report-wrap' : 'report-wrap'}>
        <LayoutB
          rowSize={['10%', '150px', '90%']}
          leftSlot={<ReportTypeList />}
          rightSlot={
            <div
              className={
                currentMenuKey === '2' ? 'finance-builder-content' : 'report-builder-content'
              }
            >
              <LayoutB
                rowSize={['20%', '150px', '90%']}
                leftSlot={
                  currentMenuKey === '2' ? (
                    <TreeView
                      id="treeview"
                      width={'100%'}
                      height={'calc(100vh - 150px)'}
                      dataStructure="plain"
                      ref={treeViewRef}
                      items={disclosureTablesData}
                      displayExpr="title"
                      parentIdExpr="pid"
                      keyExpr="id"
                      selectByClick={true}
                      selectAllText="全选"
                      showCheckBoxesMode={'selectAll'}
                      virtualModeEnabled={true}
                      selectionMode={'multiple'}
                      selectNodesRecursive={false}
                      searchEnabled={true}
                      onSelectionChanged={treeViewSelectionChanged}
                    />
                  ) : (
                    <div />
                  )
                }
              />
            </div>
          }
        />
      </div>
    </div>
  );
};

export default ReportBuilder1;
